import { useBaseApi } from '/@/api/base';

// 计划视图接口服务
export const usePlanViewApi = () => {
	const baseApi = useBaseApi('planView');
	return {

		// 获取更新信息分析数据(POST，带筛选参数) - 新增更新分析接口
		getUpdateAnalysisData: (data: UpdateAnalysisInput = {}, cancel: boolean = false) =>
			baseApi.request(
				{
					url: baseApi.baseUrl + 'GetUpdateAnalysisData',
					method: 'post',
					data,
				},
				cancel
			),


		// 获取计划清单数据（分页）
		getPlanLists: (data: PlanListInput = {}, cancel: boolean = false) =>
			baseApi.request(
				{
					url: baseApi.baseUrl + 'planLists',
					method: 'post',
					data,
				},
				cancel
			),

		// 导出计划清单Excel
		exportPlanListsExcel: (data: PlanListInput = {}, cancel: boolean = false) =>
			baseApi.request(
				{
					url: baseApi.baseUrl + 'exportPlanListsExcel',
					method: 'post',
					data,
					responseType: 'blob', // 设置响应类型为blob以支持文件下载
				},
				cancel
			),

		// ========== 新的模块化API接口 ==========
		// 获取统计卡片数据（仅卡片和时间进度）
		getStatisticsCards: (data: BusinessMonthFilter = {}, cancel: boolean = false) =>
			baseApi.request(
				{
					url: baseApi.baseUrl + 'statisticsCards',
					method: 'post',
					data,
				},
				cancel
			),

		// 获取月度图表数据（仅月度折线图）
		getMonthlyChart: (data: BusinessMonthFilter = {}, cancel: boolean = false) =>
			baseApi.request(
				{
					url: baseApi.baseUrl + 'monthlyChart',
					method: 'post',
					data,
				},
				cancel
			),

		// 获取区域分析数据（区域对比图表）
		getAreaAnalysis: (data: BusinessMonthFilter = {}, cancel: boolean = false) =>
			baseApi.request(
				{
					url: baseApi.baseUrl + 'areaAnalysis',
					method: 'post',
					data,
				},
				cancel
			),

		// 获取分类分析数据（分类对比图表）
		getCategoryAnalysis: (data: BusinessMonthFilter = {}, cancel: boolean = false) =>
			baseApi.request(
				{
					url: baseApi.baseUrl + 'categoryAnalysis',
					method: 'post',
					data,
				},
				cancel
			),

		// ========= 周期分析：树形/透视 =========
		getCycleTree: (data: CycleTreeRequest, cancel: boolean = false) =>
			baseApi.request(
				{
					url: baseApi.baseUrl + 'cycleTree',
					method: 'post',
					data,
				},
				cancel
			),
		getCyclePivot: (data: CyclePivotRequest, cancel: boolean = false) =>
			baseApi.request(
				{
					url: baseApi.baseUrl + 'cyclePivot',
					method: 'post',
					data,
				},
				cancel
			),

		// 周期分析导出（树形当前层）
		exportCycleTree: (data: CycleTreeExportRequest, cancel: boolean = false) =>
			baseApi.request(
				{
					url: baseApi.baseUrl + 'exportCycleTreeExcel',
					method: 'post',
					data,
					responseType: 'arraybuffer',
				},
				cancel
			),

		// 周期分析：统计聚合（仅聚合数据，不含任何甘特明细）
		getCycleSummary: (data: CycleSummaryRequest, cancel: boolean = false) =>
			baseApi.request(
				{
					url: baseApi.baseUrl + 'cycleSummary',
					method: 'post',
					data,
				},
				cancel
			),

		// 周期分析：甘特图
		getGantt: (data: GanttRequest, cancel: boolean = false) =>
			baseApi.request(
				{
					url: baseApi.baseUrl + 'gantt',
					method: 'post',
					data,
				},
				cancel
			),

	};
};

// 计划统计筛选参数类型
export interface PlanViewInput {
	/**
	 * 筛选月份，格式如 '2025-07'
	 */
	workTime?: string;
	// 分类
	className?: number;
	// 区域
	workAreaId?: number;
}

// 计划统计数据返回类型
export interface PlanStartStatisticsDto {
	month: string;
	planStartTotal: number;
	planEndTotal: number;
	actualStartTotal: number;
	actualEndTotal: number;
	startRate: number;
	endRate: number;
}





// 更新分析输入参数类型
export interface UpdateAnalysisInput {
	/**
	 * 筛选月份，格式如 '2025-07'
	 */
    workTime?: string; // 兼容保留，优先使用 rangeStart/rangeEnd
    // 可选：显式业务范围（起止时间，前端已计算好的范围）
    rangeStart?: string;
    rangeEnd?: string;
	// 分类筛选
	className?: number;
	// 区域筛选
	workAreaId?: number;
}

// 更新分析输出数据类型
export interface UpdateAnalysisOutput {
	// 作业区ID
	workAreaId?: number;
	// 作业区名称
	workAreaName: string;
	// 总记录数
	totalCount: number;
	// 最后创建时间
	lastCreateTime?: string;
	// 最后更新时间
	lastUpdateTime?: string;
	// 最后更新人
	lastUpdateUserName?: string;
	// 今日更新状态
	todayUpdateStatus: string;
}

// ======== 周期统计 DTO ========
export interface CycleSummaryRequest {
  filters: CycleCommonFilters;
  timeField: TimeFieldMode;
  timeMatch: TimeMatchMode;
  dims: string[];
  pageIndex?: number;
  pageSize?: number;
  targetKeyPath?: string[];
}

export interface CycleSummaryRow {
  id: string;
  keyPath: string[];
  label: string;
  displayKeyPath?: string[];
  displayLabel?: string;
  planCycleAvgDays?: number;
  actualCycleAvgDays?: number;
  planCycleSumDays?: number;
  actualCycleSumDays?: number;
  actualWorkDays?: number;
  idleGapDays?: number;
  fullCycleDays?: number;
  planSpanDays?: number;
  actualSpanDays?: number;
  itemCount: number;
  completedCount: number;
  inProgressCount: number;
}

export interface CycleSummaryResponse {
  rows: CycleSummaryRow[];
  total: number;
  pageIndex: number;
  pageSize: number;
}

// 旧甘特相关接口与类型已移除


// 延期范围枚举
export enum DelayRangeEnum {
	Light = 1, // 轻微延期：1-3天
	Medium = 2, // 中等延期：4-7天
	Severe = 3, // 严重延期：7天以上
	All = 4, // 全部延期
}

// 计划清单输入参数类型
export interface PlanListInput {
	/**
	 * 筛选月份，格式如 '2025-07'
	 */
    workTime?: string; // 兼容保留，优先使用 rangeStart/rangeEnd
    // 可选：显式业务范围（起止时间，前端已计算好的范围）
    rangeStart?: string;
    rangeEnd?: string;
	// 分类筛选
	className?: number;
	// 区域筛选
	workAreaId?: number;
	// 清单类型：actualStart, actualEnd, delayStart, delayEnd, planStart, planEnd
	listType: string;
	// 分页参数
	pageIndex?: number;
	pageSize?: number;
	// 延期范围筛选（仅对delayStart和delayEnd类型有效）
	delayRange?: DelayRangeEnum;
}

// 计划清单项数据类型
export interface PlanListItem {
	// 船号
	ch: string;
	// 分段名称
	fd: string;
	// 分类名称
	className: string;
	// 区域名称
	workAreaName: string;
	// 劳务队名称
	team: string;
	// 计划开工日期
	planStart?: string;
	// 实际开工日期
	actualStart?: string;
	// 计划完工日期
	planEnd?: string;
	// 实际完工日期
	actualEnd?: string;
	// 延期天数（仅对延期类型listType有效）
	delayDays: number;
}

// 计划清单返回数据类型
export interface PlanListOutput {
	// 清单数据
	items: PlanListItem[];
	// 总数量
	total: number;
	// 当前页
	pageIndex: number;
	// 页大小
	pageSize: number;
}

// ========== 新的模块化API数据类型 ==========

// 业务月度筛选参数类型
export interface BusinessMonthFilter {
	// 业务月份，格式如 '2025-07'
    workTime?: string; // 兼容保留，优先使用 rangeStart/rangeEnd
    // 可选：显式业务范围（起止时间，前端已计算好的范围）
    rangeStart?: string;
    rangeEnd?: string;
	// 分类筛选
	className?: number;
	// 区域筛选
	workAreaId?: number;
}

// ========== 周期分析类型 ==========

export type TimeFieldMode = 'both' | 'plan' | 'actual';
export type TimeMatchMode = 'intersects' | 'startWithin' | 'endWithin';

export interface CycleCommonFilters {
  workTime?: string;
  rangeStart?: string;
  rangeEnd?: string;
  className?: number;
  workAreaId?: number;
  shipNos?: string[];
  sections?: string[];
  keyword?: string;
  onlyCompleted?: boolean;
  ignoreNegative?: boolean;
}

export interface SortSpec { field: string; desc?: boolean }

export interface CycleTreeRequest {
  filters: CycleCommonFilters;
  timeField?: TimeFieldMode;
  timeMatch?: TimeMatchMode;
  dims: string[]; // ['ship','section','category','region','sectionFirst']
  lazy?: boolean;
  parentKeyPath?: string[];
  pageIndex?: number;
  pageSize?: number;
  sort?: SortSpec[];
}

export interface CycleTreeNode {
  id: string;
  keyPath: string[];
  level: number;
  labels: Record<string, string | null>;
  itemCount: number;
  completedCount: number;
  inProgressCount: number;
  planCycleAvgDays?: number;
  actualCycleAvgDays?: number;
  planCycleSumDays?: number;
  actualCycleSumDays?: number;
  varianceSumDays?: number;
  varianceAvgDays?: number;
  planSpanDays?: number;
  actualSpanDays?: number;
  hasChildren: boolean;
  children?: CycleTreeNode[];
}

export interface CycleTreeResponse {
  nodes: CycleTreeNode[];
  total: number;
  pageIndex: number;
  pageSize: number;
}

export interface CycleTreeExportRequest extends CycleTreeRequest {
  exportAll?: boolean; // true 导出当前层全部，忽略分页；false 仅导出当前页
}

export interface CyclePivotRequest {
  filters: CycleCommonFilters;
  timeField?: TimeFieldMode;
  timeMatch?: TimeMatchMode;
  rowDims: string[];
  colDims: string[];
  showTotals?: boolean;
}

export interface PivotHeader { keyPath: string[]; label: string; level: number }
export interface PivotCell {
  r: number;
  c: number;
  itemCount: number;
  planCycleAvgDays?: number;
  actualCycleAvgDays?: number;
  planCycleSumDays?: number;
  actualCycleSumDays?: number;
  varianceSumDays?: number;
  varianceAvgDays?: number;
}
export interface CyclePivotResponse { rows: PivotHeader[]; cols: PivotHeader[]; cells: PivotCell[] }

// 卡片项数据类型
export interface CardItem {
	// 卡片类型
	cardType: string;
	// 卡片标题
	title: string;
	// 卡片副标题
	subtitle: string;
	// 计划总数
	planCount: number;
	// 实际完成数
	actualCount: number;
	// 完成率
	rate: number;
	// 图标类型
	iconType: string;
	// 颜色
	color: string;
}

// 统计卡片响应数据类型
export interface StatisticsCardsResponse {
	// 4个统计卡片数据
	cards: CardItem[];
	// 时间进度率
	timeProgressRate: number;
	// 已过天数
	passedDays: number;
	// 总天数
	totalDays: number;
	// 加载时间
	loadTime: string;
	// 缓存过期时间
	cacheExpiry: string;
}

// 每日数据点类型
export interface DailyPoint {
	// 日期
	date: string;
	// 计划开工
	planStart: number;
	// 计划完工
	planEnd: number;
	// 实际开工
	actualStart: number;
	// 实际完工
	actualEnd: number;
}

// 月度图表响应数据类型
export interface MonthlyChartResponse {
	// 月度数据
	monthlyData: DailyPoint[];
	// 业务月份开始日期
	businessMonthStart: string;
	// 业务月份结束日期
	businessMonthEnd: string;
	// 加载时间
	loadTime: string;
	// 缓存过期时间
	cacheExpiry: string;
}

// 区域项数据类型
export interface AreaItem {
	// 区域ID
	areaId: number;
	// 区域名称
	areaName: string;
	// 统计数据
	statistics: {
		planStart: number;
		planEnd: number;
		actualStart: number;
		actualEnd: number;
		startRate: number;
		endRate: number;
	};
	// 图表数据
	chartData: DailyPoint[];
}

// 区域分析响应数据类型
export interface AreaAnalysisResponse {
	// 区域列表
	areas: AreaItem[];
	// 加载时间
	loadTime: string;
	// 缓存过期时间
	cacheExpiry: string;
}

// 分类项数据类型
export interface CategoryItem {
	// 分类ID
	categoryId: number;
	// 分类名称
	categoryName: string;
	// 统计数据
	statistics: {
		planStart: number;
		planEnd: number;
		actualStart: number;
		actualEnd: number;
		startRate: number;
		endRate: number;
	};
	// 图表数据
	chartData: DailyPoint[];
}

// 分类分析响应数据类型
export interface CategoryAnalysisResponse {
	// 分类列表
	categories: CategoryItem[];
	// 加载时间
	loadTime: string;
	// 缓存过期时间
	cacheExpiry: string;
}

// ========== 甘特图类型 ==========

export interface PlanActualRangeFilters {
  planStartFrom?: string; planStartTo?: string;
  planEndFrom?: string; planEndTo?: string;
  actualStartFrom?: string; actualStartTo?: string;
  actualEndFrom?: string; actualEndTo?: string;
}

export interface GanttRequest {
  filters: CycleCommonFilters & PlanActualRangeFilters;
  timeField: TimeFieldMode;
  timeMatch: TimeMatchMode;
  dims: string[];
  parentKeyPath?: string[];
  pageIndex?: number;
  pageSize?: number;
  laneMode?: 'plan'|'actual'|'both';
  onlyDelayed?: boolean;
  lazy?: boolean;
  expandDepth?: number;
  expandAll?: boolean;
}

export interface GanttItem {
  id: string;
  label: string;
  keyPath?: string[];
  planStart?: string;
  planEnd?: string;
  actualStart?: string;
  actualEnd?: string;
  progress?: number;
  status?: 'onTime'|'delayed'|'early'|'inProgress'|'notStarted';
}

export interface GanttLane { id: string; label: string; path: string[]; items: GanttItem[] }

export interface GanttResponse { lanes: GanttLane[]; timeStart: string; timeEnd: string; totalItems: number; totalNodes?: number }
